package com.yuke.cloud.service.uac.controller.frontend;

import com.google.common.base.Preconditions;
import com.yuke.cloud.common.base.dto.LoginAuthDto;
import com.yuke.cloud.common.core.annotation.LogAnnotation;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.uac.dto.*;
import com.yuke.cloud.service.uac.entity.AccMenu;
import com.yuke.cloud.service.uac.service.AccMenuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.MediaType;
import com.yuke.cloud.common.core.support.BaseController;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
* Created by wg on 2018/10/31.
*/
@Api(value = "WEB - AccMenuController", tags = "处理AccMenu相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/acc/menu")
public class AccMenuController extends BaseController {
    @Resource
    private AccMenuService accMenuService;

    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "accMenu", value = "该数据记录的POJO") @RequestBody AccEditMenuDto accMenuAddDto) {
//        accMenuService.save(accMenu);
//        return WrapMapper.ok();

        return UpdateOrAddMenu(accMenuAddDto);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {

        Preconditions.checkArgument(id != null, "菜单ID不能为空");

        // 判断此菜单是否有子节点
        boolean hasChild = accMenuService.checkMenuHasChildMenu(id);
        if (hasChild) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, "此菜单含有子菜单, 请先删除子菜单");
        }

//        accMenuService.deleteById(id);
//        return WrapMapper.ok();
        int result = accMenuService.deleteAccMenuById(id);
        return super.handleResult(result);
    }

    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "accMenu", value = "需要修改的内容") @RequestBody AccEditMenuDto accMenuAddDto) {
//        accMenuService.update(accMenu);
//        return WrapMapper.ok();
        return UpdateOrAddMenu(accMenuAddDto);
    }

    private Wrapper UpdateOrAddMenu(AccEditMenuDto accMenuAddDto) {
        AccMenu accMenu = new AccMenu();
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        BeanUtils.copyProperties(accMenuAddDto, accMenu);
        accMenuService.saveAccMenu(accMenu, loginAuthDto);
        return WrapMapper.ok(accMenu.getMenuId());
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<AccMenu> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
//        AccMenu accMenu = accMenuService.findById(id);
        AccMenu accMenu = accMenuService.getViewMenuById(id);
        return WrapMapper.ok(accMenu);
    }

    @GetMapping
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<AccMenu>> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                    @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        // List<AccMenu> list = accMenuService.findAll();
        List<AccMenu> list = accMenuService.getAllMenuListByUserId(getLoginAuthDto().getUserId(), null);
        if (list == null) {
            list = new ArrayList<AccMenu>();
        }
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    /**
     * 根据id修改菜单的禁用状态
     *
     * @param accMenuEnableDto the acc menu status dto
     *
     * @return the wrapper
     */
    @PostMapping(value = "/modifyEnable")
    @ApiOperation(httpMethod = "POST", value = "修改菜单状态")
    @LogAnnotation
    public Wrapper updateAccMenuEnableById(@ApiParam(name = "accMenuEnableDto", value = "修改菜单状态Dto") @RequestBody AccMenuEnableDto accMenuEnableDto) {
        logger.info("根据id修改菜单的禁用状态 accMenuEnableDto={}", accMenuEnableDto);
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        accMenuService.updateUacMenuStatusById(accMenuEnableDto, loginAuthDto);
        return WrapMapper.ok();
    }

    /**
     * 检测菜单编码是否已存在
     *
     * @param accMenuCheckCodeDto the uac menu check code dto
     *
     * @return the wrapper
     */
    @PostMapping(value = "/checkMenuCode")
    @ApiOperation(httpMethod = "POST", value = "检测菜单编码是否已存在")
    public Wrapper<Boolean> checkUacMenuActionCode(@ApiParam(name = "uacMenuCheckCodeDto", value = "id与url") @RequestBody AccMenuCheckCodeDto accMenuCheckCodeDto) {
        logger.info("校验菜单编码唯一性 uacMenuCheckCodeDto={}", accMenuCheckCodeDto);

        Long id = accMenuCheckCodeDto.getMenuId();
        String menuCode = accMenuCheckCodeDto.getMenuCode();

        Example example = new Example(AccMenu.class);
        Example.Criteria criteria = example.createCriteria();

        if (id != null) {
            criteria.andNotEqualTo("menuId", id);
        }
        criteria.andEqualTo("menuCode", menuCode);

        int result = accMenuService.selectCountByExample(example);
        return WrapMapper.ok(result < 1);
    }

    /**
     * 检测菜单名称唯一性
     *
     * @param accMenuCheckNameDto the acc menu check name dto
     *
     * @return the wrapper
     */
    @PostMapping(value = "/checkMenuName")
    @ApiOperation(httpMethod = "POST", value = "检测菜单名称唯一性")
    public Wrapper<Boolean> checkUacMenuName(@ApiParam(name = "accMenuCheckNameDto", value = "id与name") @RequestBody AccMenuCheckNameDto accMenuCheckNameDto) {
        logger.info("校验菜单名称唯一性 uacMenuCheckNameDto={}", accMenuCheckNameDto);
        Long id = accMenuCheckNameDto.getMenuId();
        Long pid = accMenuCheckNameDto.getParentId();
        String menuName = accMenuCheckNameDto.getMenuName();

        Example example = new Example(AccMenu.class);
        Example.Criteria criteria = example.createCriteria();

        if (id != null) {
            criteria.andNotEqualTo("menuId", id);
        }
        criteria.andEqualTo("menuName", menuName);
        criteria.andEqualTo("parentId", pid);

        int result = accMenuService.selectCountByExample(example);
        return WrapMapper.ok(result < 1);
    }


    /**
     * 检测菜单URL唯一性
     *
     * @param accMenuCheckUrlDto the uac menu check url dto
     *
     * @return the wrapper
     */
    @PostMapping(value = "/checkMenuUrl")
    @ApiOperation(httpMethod = "POST", value = "检测菜单URL唯一性")
    public Wrapper<Boolean> checkUacMenuUrl(@ApiParam(name = "uacMenuCheckUrlDto", value = "id与url") @RequestBody AccMenuCheckUrlDto accMenuCheckUrlDto) {
        logger.info("检测菜单URL唯一性 accMenuCheckUrlDto={}", accMenuCheckUrlDto);

        Long id = accMenuCheckUrlDto.getMenuId();
        String url = accMenuCheckUrlDto.getUrl();

        Example example = new Example(AccMenu.class);
        Example.Criteria criteria = example.createCriteria();

        if (id != null) {
            criteria.andNotEqualTo("menuId", id);
        }
        criteria.andEqualTo("url", url);

        int result = accMenuService.selectCountByExample(example);
        return WrapMapper.ok(result < 1);
    }
}
